package com.iqilu.ksd.fragment;

import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.Toast;

import com.andview.refreshview.XRefreshView;
import com.andview.refreshview.XRefreshViewLiveFooter;
import com.google.gson.reflect.TypeToken;
import com.iqilu.ksd.MyApplication;
import com.iqilu.ksd.R;
import com.iqilu.ksd.adapter.LiveCommentAdapter;
import com.iqilu.ksd.bean.CommentBean;
import com.iqilu.ksd.bean.UserBean;
import com.iqilu.ksd.constant.Api;
import com.iqilu.ksd.utils.JSONUtils;
import com.iqilu.ksd.utils.KeyboardUtils;
import com.iqilu.ksd.widget.LigDialog;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by Coofee on 2016/11/21.
 */

public class LiveCommentFragment extends BaseFragment implements View.OnClickListener{

    private static final String TAG = "LiveCommentFragment";

    private int id;
    private UserBean user;
    private String type = "live";
    private ImageView imgEmpty;
    private ImageView btSubmit;
    private EditText etEmoji;
    private FrameLayout layEmoji;
    private ArrayList<CommentBean> list;
    private XRefreshView xRefreshView;
    private RecyclerView rvList;

    private LigDialog ligDialog;
    private LiveCommentAdapter adapter;

    private Timer timer;
    private TimerTask timerTask;
    private boolean isLoading = false;

    private static final int LOAD_NEW = 1;
    private static final int LOAD_OLD = 2;
    private static final int PERPAGE = 20;

    private static final int AUTO_LOADDATA = 1;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        id = bundle == null ? 0 : bundle.getInt("id");
        user = ((MyApplication) getActivity().getApplication()).getUser();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_livecomment, null);
        imgEmpty = getView(view, R.id.img_empty);
        btSubmit = getView(view, R.id.bt_submit);
        etEmoji = getView(view, R.id.et_emoji);
        layEmoji = getView(view, R.id.layout_emoji);
        xRefreshView = getView(view, R.id.xRefreshView);
        rvList = getView(view, R.id.rv_list);
        btSubmit.setOnClickListener(this);

        LinearLayoutManager layoutManager = new LinearLayoutManager(context);
        layoutManager.setOrientation(OrientationHelper.VERTICAL);
        rvList.setLayoutManager(layoutManager);
        rvList.setHasFixedSize(true);
        adapter = new LiveCommentAdapter(context);
        adapter.setCustomLoadMoreView(new XRefreshViewLiveFooter(context));

        xRefreshView.setPullRefreshEnable(true);
        xRefreshView.setPullLoadEnable(true);
        xRefreshView.setMoveForHorizontal(true);
        xRefreshView.enableReleaseToLoadMore(true);
        xRefreshView.enableRecyclerViewPullUp(true);
        xRefreshView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {
            @Override
            public void onRefresh() {
                super.onRefresh();
                Log.i(TAG,"onRefresh...");
                new LoadData(LOAD_NEW).execute();
            }

            @Override
            public void onLoadMore(boolean isSilence) {
                super.onLoadMore(isSilence);
                Log.i(TAG,"onLoadMore...");
                new LoadData(LOAD_OLD).execute();
            }
        });
        rvList.setAdapter(adapter);

        list = new ArrayList<CommentBean>();
        new LoadData(LOAD_NEW).execute();
        autoLoad();
        return view;
    }

    private void autoLoad() {
        timer = new Timer();
        timerTask = new TimerTask() {
            @Override
            public void run() {
                Message message = new Message();
                message.what = AUTO_LOADDATA;
                handler.sendMessage(message);
            }
        };
        timer.schedule(timerTask, 2000, 2000);
    }

    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == AUTO_LOADDATA && !isLoading) {
                new LoadData(LOAD_NEW).execute();
            }
        }
    };


    private void submit(){
        if (!TextUtils.isEmpty(etEmoji.getText().toString())) {
            if (user == null || user.getId() < 1) {
                Toast.makeText(context, R.string.not_login, Toast.LENGTH_SHORT).show();
                return;
            } else {
                addComment(etEmoji.getText().toString());
            }
        } else {
            Toast.makeText(context, R.string.live_comment_empty, Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_submit:
                submit();
                break;
            default:
                break;
        }
    }

    class LoadData extends AsyncTask<Void, Void, Void> {

        private ArrayList<CommentBean> result;
        int fb = 1;
        int listorder = 0;

        public LoadData(int fb) {
            this.fb = fb;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            isLoading = true;
            if (list.size() == 0) {
                listorder = 0;
            } else {
                if (fb == LOAD_NEW) {
                    listorder = list.get(0).getId();
                } else {
                    listorder = list.get(list.size() - 1).getId();
                }
            }
        }

        @Override
        protected Void doInBackground(Void... params) {
            Response response = null;
            String url = Api.URL_COMMENT_BYRANGE + "?id=" + listorder + "&fb=" + fb + "&articleid=" + id + "&catid=0&type=" + type;
            try {
                response = OkHttpUtils.get().url(url).tag(this).build().execute();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (response != null) {
                try {
                    result = JSONUtils.requestList(response.body().string(), "data", new TypeToken<ArrayList<CommentBean>>() {
                    });
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            Log.i(TAG,"onPostExecute fb="+fb);
            if(fb == LOAD_NEW) {
                xRefreshView.stopRefresh();
            }else {
                xRefreshView.stopLoadMore();
            }
            imgEmpty.setVisibility(View.GONE);
            if (result == null || result.size() == 0) {
                if (listorder == 0) {
                    imgEmpty.setVisibility(View.VISIBLE);
                }
                isLoading = false;
                return;
            }
            if (fb == LOAD_NEW) {
                result.addAll(list);
                list = result;
            } else {
                list.addAll(result);
            }
            adapter.setData(list);
            adapter.notifyDataSetChanged();
            isLoading = false;
        }

    }

    private void addComment(String comment) {
        String url = Api.URL_COMMENT;
        OkHttpUtils
                .post()
                .url(url)
                .addParams("articleid", "" + id)
                .addParams("catid", "0")
                .addParams("type", "live")
                .addParams("comment", Uri.encode(comment))
                .tag(this)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onBefore(Request request, int id) {
                        super.onBefore(request, id);
                        ligDialog = new LigDialog(context, getString(R.string.waiting));
                        ligDialog.show();
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        ligDialog.dismiss();
                        Toast.makeText(context, R.string.live_comment_fail, Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        ligDialog.dismiss();
                        int status = 0;
                        JSONObject jsonObject = null;
                        try {
                            jsonObject = new JSONObject(response);
                            status = jsonObject.getInt("status");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        if (status == 1) {
                            etEmoji.setText("");
                            Toast.makeText(context, R.string.live_comment_success, Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(context, R.string.live_comment_fail, Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
        }
    }
}
